package com.emath.activities;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.emath.HelpDialog;
import com.lnl.R;
import com.emath.objects.Card;
import com.emath.objects.Username;
import com.emath.shared.Globals;
import com.emath.shared.RestClient;

public class CollectionMgr extends Activity {
	/** Called when the activity is first created. */
	LinearLayout collectionTable, playDeckTable;
	HorizontalScrollView collectionScrollView, playDeckScrollView;
	int numOfCards = 0, cardFocus = 0;
	ImageView display;
	TextView cardName, type, cost1, mind1, mind2, mind3, charm1, charm2,
			charm3, strength1, strength2, strength3, levelUp, special,
			specialEffect, cost, wiki, uniqueID, playDeck, numOfCardsInDeck;
	Card cardObj = new Card();
	MediaPlayer cardSound = new MediaPlayer();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.collection);
		cardSound = MediaPlayer.create(CollectionMgr.this, R.raw.soundchoice);
		Typeface tf = Typeface.createFromAsset(getAssets(),
				"fonts/Capture_it.ttf");

		Button setFocus = (Button) findViewById(R.id.changePlayDeckBtn);
		setFocus.setTypeface(tf);

		TextView tempTV;
		tempTV = (TextView) findViewById(R.id.cmFunctionTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.cmMindTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.cmCharmTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.cmStrengthTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.cmCostTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.cmSpecialTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.cmLevelUpTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.cmPlayDeckTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.cmWikiTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.numOfCardsInDeckTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.cmPlayDeckLayoutTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.cmCollectionTitle);
		tempTV.setTypeface(tf);

		// This while loop simply ensures that the collectionObj is done
		// populating before proceeding with the display of the CollectionMgr
		// contents.
		while (!Globals.collectionObj.getObjectState().equals("free")) {
			try {// A sleep thread is used to cut down on processor time used
					// here
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		collectionScrollView = (HorizontalScrollView) findViewById(R.id.cmCollectionHorizontalScrollView);
		playDeckScrollView = (HorizontalScrollView) findViewById(R.id.cmPlayDeckHorizontalScrollView);
		display = (ImageView) findViewById(R.id.cmSelectedCardImage);
		display.setPadding(3, 3, 3, 3);
		display.setAdjustViewBounds(true);
		display.setScaleType(ScaleType.CENTER_INSIDE);
		cardName = (TextView) findViewById(R.id.cmCardNameData);
		type = (TextView) findViewById(R.id.cmFunctionData);
		mind1 = (TextView) findViewById(R.id.cmMindData);
		charm1 = (TextView) findViewById(R.id.cmCharmData);
		strength1 = (TextView) findViewById(R.id.cmStrengthData);
		cost1 = (TextView) findViewById(R.id.cmCostData);
		special = (TextView) findViewById(R.id.cmSpecialData);
		levelUp = (TextView) findViewById(R.id.cmLevelUpData);
		playDeck = (TextView) findViewById(R.id.cmPlayDeckData);
		numOfCardsInDeck = (TextView) findViewById(R.id.numOfCardsInDeck);
		uniqueID = (TextView) findViewById(R.id.cmUniqueID);
		wiki = (TextView) findViewById(R.id.cmWikiData);

		for (int i = 0; i < Globals.collectionObj.getCardList().size(); i++) {
			if (Globals.collectionObj.getCardList().get(i).getPlayDeck()) {
				numOfCards++;
			}
		}
		Globals.collectionObj.setNumOfCardsInDeck(numOfCards);
		numOfCardsInDeck.setText("" + numOfCards);

		setFocus.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				MediaPlayer buttonSound = new MediaPlayer();
				buttonSound = MediaPlayer.create(CollectionMgr.this,
						R.raw.button_click);
				buttonSound.start();
				int n = Globals.collectionObj.getNumOfCardsInDeck();
				if (playDeck.getText().equals("Yes")) {
					playDeck.setText("No");
					Globals.collectionObj.setNumOfCardsInDeck(n - 1);
					n--;
					Globals.collectionObj.getCardList().get(cardFocus)
							.setPlayDeck(false);
					try {
						Globals.collectionObj.getCardList().get(cardFocus)
								.alterPlayDeck();
						while (Globals.collectionObj.getCardList()
								.get(cardFocus).getObjectState()
								.equals("working")) {
							Thread.sleep(50);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					numOfCardsInDeck.setText("" + n);
					Toast tooltip = Toast
							.makeText(
									getApplicationContext(),
									"If you do not replace this card in your play deck, random cards will be chosen for you.",
									Toast.LENGTH_LONG);
					tooltip.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL,
							0, 200);
					tooltip.show();
				} else if (n < 20) {
					playDeck.setText("Yes");
					Globals.collectionObj.setNumOfCardsInDeck(n + 1);
					n++;
					Globals.collectionObj.getCardList().get(cardFocus)
							.setPlayDeck(true);
					try {
						Globals.collectionObj.getCardList().get(cardFocus)
								.alterPlayDeck();
						while (Globals.collectionObj.getCardList()
								.get(cardFocus).getObjectState()
								.equals("working")) {
							Thread.sleep(50);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					numOfCardsInDeck.setText("" + n);
					Toast tooltip = Toast.makeText(getApplicationContext(),
							"You have added a card to your play deck.",
							Toast.LENGTH_LONG);
					tooltip.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL,
							0, 200);
					tooltip.show();
				} else if (n == 20) {
					Toast tooltip = Toast
							.makeText(
									getApplicationContext(),
									"You have chosen a maximum number of cards for your play deck.",
									Toast.LENGTH_LONG);
					tooltip.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL,
							0, 200);
					tooltip.show();
				}
				playDeckTable.removeAllViews();
				collectionTable.removeAllViews();

				fillTables();
			}

		});

		fillTables();

	}

	@Override
	protected void onResume() {
		// Refresh
		super.onResume();
		findViewById(android.R.id.content).invalidate();
	}

	void fillTables() {
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		layoutParams.setMargins(5, 0, 5, 0);
		playDeckTable = new LinearLayout(this);
		playDeckTable = (LinearLayout) findViewById(R.id.cmPlayDeckLayout);
		collectionTable = new LinearLayout(this);
		collectionTable = (LinearLayout) findViewById(R.id.cmCollectionLayout);
		for (int current = 0; current < Globals.collectionObj.getCardList()
				.size(); current++) {

			ImageView image1 = new ImageView(this);
			image1.setPadding(2, 2, 2, 2);
			image1.setScaleType(ScaleType.CENTER_INSIDE);
			image1.setAdjustViewBounds(true);
			image1.setImageBitmap(Globals.collectionObj.getCardList()
					.get(current).getBitmap());
			image1.setId(current);
			String function = Globals.collectionObj.getCardList().get(current)
					.getType();
			if (function.equals("Artist")) {
				image1.setBackgroundColor(Color.RED);
			} else if (function.equals("Athlete")) {
				image1.setBackgroundColor(Color.YELLOW);
			} else if (function.equals("Leader")) {
				image1.setBackgroundColor(Color.BLUE);
			} else if (function.equals("Student")) {
				image1.setBackgroundColor(Color.GREEN);
			} else {
				image1.setBackgroundColor(Color.rgb(128, 0, 128));
			}
			image1.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					cardSound.start();
					cardFocus = v.getId();
					cardObj = Globals.collectionObj.getCardList()
							.get(v.getId());
					display.setImageBitmap(cardObj.getBitmap());
					String function = cardObj.getType();
					if (function.equals("Artist")) {
						display.setBackgroundColor(Color.RED);
					} else if (function.equals("Athlete")) {
						display.setBackgroundColor(Color.YELLOW);
					} else if (function.equals("Leader")) {
						display.setBackgroundColor(Color.BLUE);
					} else if (function.equals("Student")) {
						display.setBackgroundColor(Color.GREEN);
					} else {
						display.setBackgroundColor(Color.rgb(128, 0, 128));
					}
					uniqueID.setText(cardObj.getUniqueID());
					cardName.setText(cardObj.getCardName());
					type.setText(cardObj.getType());
					cost1.setText(cardObj.getCost());
					mind1.setText(cardObj.getMind1());
					charm1.setText(cardObj.getCharm1());
					strength1.setText(cardObj.getStrength1());
					special.setText(cardObj.getSpecial());
					levelUp.setText(cardObj.getLevelUp());
					playDeck.setText(cardObj.getPlayDeck().equals(true) ? "Yes"
							: "No");
					wiki.setText(cardObj.getWiki());
					Linkify.addLinks(wiki, Linkify.ALL);
				}
			});
			if (Globals.collectionObj.getCardList().get(current).equals(null) ? false
					: Globals.collectionObj.getCardList().get(current)
							.getPlayDeck()) {
				playDeckTable.setHorizontalFadingEdgeEnabled(true);
				playDeckTable.setVerticalFadingEdgeEnabled(true);
				playDeckTable.setFadingEdgeLength(100);
				playDeckTable.addView(image1, layoutParams);
			} else {
				collectionTable.setHorizontalFadingEdgeEnabled(true);
				collectionTable.setVerticalFadingEdgeEnabled(true);
				collectionTable.setFadingEdgeLength(100);
				collectionTable.addView(image1, layoutParams);
			}

		}
	}
	public void displayhelp() {

		HelpDialog helpDialog = new HelpDialog(CollectionMgr.this);
		helpDialog.setTitle("Help contents");
		helpDialog.show();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.ingamemenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.exit:
			RestClient Connect = new RestClient();
			
			final MediaPlayer buttonSound = MediaPlayer.create(
					CollectionMgr.this, R.raw.button_click);
			buttonSound.start();
			String logout = "http://emath-project.appspot.com/emath/emathservicehttp?function=logout&userID="
					+ Username.getUser();
			Connect.connect(logout);
			if (Globals.isconnected== 0){
				Toast.makeText(CollectionMgr.this, "Connection Error", Toast.LENGTH_LONG).show();
				Globals.isconnected=1;
			}
			else{
			Connect.clear();
			finish();
			return true;
			}
		case R.id.help:
			displayhelp();
			return true;
		}
		return super.onOptionsItemSelected(item);

	}

	@Override
	protected void onPostResume() {
		if (Globals.focusedActivity.equals("CollectionMgr")) {
			if (Globals.settingsHolder[1] == 1) {
				startService(Globals.backgroundMusicService);
			}
			Globals.isMusicPlaying = true;
		}
		super.onPostResume();
	}

	@Override
	protected void onPause() {
		if (this.isFinishing()) {
			Globals.focusedActivity = "GameMenu";
		} else {
			if (Globals.settingsHolder[1] == 1) {
				stopService(Globals.backgroundMusicService);
			}
			Globals.isMusicPlaying = false;
		}
		super.onPause();
	}
}
